<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>列表管理</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text"
          @click="showAddDialog"
        >
          添加数据
        </el-button>
      </div>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="名称">
          <el-input v-model="searchForm.name" placeholder="请输入名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
            <el-option label="活跃" value="active"></el-option>
            <el-option label="禁用" value="disabled"></el-option>
            <el-option label="待审核" value="pending"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-input-number 
            v-model="searchForm.priority" 
            :min="1" 
            :max="10"
            controls-position="right"
            placeholder="优先级"
          ></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="filteredItems"
        border
        style="width: 100%"
        v-loading="loading"
        @sort-change="handleSortChange"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          sortable
        ></el-table-column>
        <el-table-column
          prop="name"
          label="名称"
          sortable
        ></el-table-column>
        <el-table-column
          prop="description"
          label="描述"
        ></el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="120"
          sortable
          :filters="[
            { text: '活跃', value: 'active' },
            { text: '禁用', value: 'disabled' },
            { text: '待审核', value: 'pending' }
          ]"
          :filter-method="filterStatus"
        >
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="priority"
          label="优先级"
          width="120"
          sortable
        >
          <template slot-scope="scope">
            <el-rate
              v-model="scope.row.priority"
              disabled
              :max="10"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              text-color="#ff9900"
              score-template="{value}"
            ></el-rate>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
          sortable
        >
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        class="pagination"
      ></el-pagination>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="活跃" value="active"></el-option>
            <el-option label="禁用" value="disabled"></el-option>
            <el-option label="待审核" value="pending"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number 
            v-model="form.priority" 
            :min="1" 
            :max="10"
            controls-position="right"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import IndexedDB from './utils/indexedDB';

export default {
  data() {
    return {
      db: null,
      items: [],
      filteredItems: [],
      loading: false,
      dialogVisible: false,
      dialogTitle: '添加数据',
      isEdit: false,
      form: {
        name: '',
        description: '',
        status: 'active',
        priority: 5
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        priority: [
          { type: 'number', required: true, message: '请设置优先级', trigger: 'blur' },
          { type: 'number', min: 1, max: 10, message: '范围1-10', trigger: 'blur' }
        ]
      },
      searchForm: {
        name: '',
        status: '',
        priority: null
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      sortProp: null,
      sortOrder: null
    };
  },
  async created() {
    this.db = new IndexedDB('VueElementUIDemo', 'items');
    await this.db.openDB();
    await this.loadItems();
  },
  methods: {
    async loadItems() {
      this.loading = true;
      try {
        this.items = await this.db.getAllItems();
        this.pagination.total = this.items.length;
        this.filterItems();
      } catch (error) {
        this.$message.error('加载数据失败: ' + error.message);
        console.error('详细错误:', error);
      } finally {
        this.loading = false;
      }
    },
    
    filterItems() {
      let filtered = [...this.items];
      
      // 搜索过滤
      if (this.searchForm.name) {
        filtered = filtered.filter(item => 
          item.name.toLowerCase().includes(this.searchForm.name.toLowerCase())
        );
      }
      
      if (this.searchForm.status) {
        filtered = filtered.filter(item => 
          item.status === this.searchForm.status
        );
      }
      
      if (this.searchForm.priority) {
        filtered = filtered.filter(item => 
          item.priority === this.searchForm.priority
        );
      }
      
      // 排序
      if (this.sortProp && this.sortOrder) {
        filtered.sort((a, b) => {
          const valA = a[this.sortProp];
          const valB = b[this.sortProp];
          if (this.sortOrder === 'ascending') {
            return valA > valB ? 1 : -1;
          } else {
            return valA < valB ? 1 : -1;
          }
        });
      }
      
      this.pagination.total = filtered.length;
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      this.filteredItems = filtered.slice(start, end);
    },
    
    filterStatus(value, row) {
      return row.status === value;
    },
    
    showAddDialog() {
      this.dialogTitle = '添加数据';
      this.isEdit = false;
      this.form = {
        name: '',
        description: '',
        status: 'active',
        priority: 5
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    
    handleEdit(index, row) {
      this.dialogTitle = '编辑数据';
      this.isEdit = true;
      this.form = {
        id: row.id,
        name: row.name,
        description: row.description,
        status: row.status,
        priority: row.priority
      };
      this.dialogVisible = true;
    },
    
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const itemData = {
              name: this.form.name,
              description: this.form.description,
              status: this.form.status,
              priority: this.form.priority,
              updateTime: new Date().getTime()
            };
            
            if (this.isEdit) {
              // 更新操作
              itemData.id = this.form.id;
              await this.db.updateItem(itemData);
              this.$message.success('更新成功');
            } else {
              // 添加操作
              itemData.createTime = new Date().getTime();
              await this.db.addItem(itemData);
              this.$message.success('添加成功');
            }
            
            this.dialogVisible = false;
            await this.loadItems();
          } catch (error) {
            this.$message.error('操作失败: ' + error.message);
            console.error('详细错误:', error);
          }
        }
      });
    },
    
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.db.deleteItem(row.id);
          this.$message.success('删除成功');
          await this.loadItems();
        } catch (error) {
          this.$message.error('删除失败: ' + error.message);
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    handleSearch() {
      this.pagination.currentPage = 1;
      this.filterItems();
    },
    
    resetSearch() {
      this.searchForm = {
        name: '',
        status: '',
        priority: null
      };
      this.handleSearch();
    },
    
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.filterItems();
    },
    
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.filterItems();
    },
    
    handleSortChange({ prop, order }) {
      this.sortProp = prop;
      this.sortOrder = order;
      this.filterItems();
    },
    
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())} 
              ${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}`;
    },
    
    padZero(num) {
      return num < 10 ? `0${num}` : num;
    },
    
    getStatusType(status) {
      switch(status) {
        case 'active': return 'success';
        case 'disabled': return 'danger';
        case 'pending': return 'warning';
        default: return 'info';
      }
    },
    
    formatStatus(status) {
      switch(status) {
        case 'active': return '活跃';
        case 'disabled': return '禁用';
        case 'pending': return '待审核';
        default: return status;
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.el-tag {
  margin-right: 5px;
}
</style>